<template>
  <!-- 后台主页布局 -->
  <div class="common-layout">
    <el-container>
      <el-header class="top">客户管理模块</el-header>
      <el-container>
        <el-aside width="240px" class="left">
          系统菜单
          <!--添加Menu菜单组件-->
          <el-menu class="el-menu-vertical-demo" @select="handlerSelect">
            <menu-item v-for="menu in menus" :key="menu.id" :item="menu"/>
          </el-menu>
        </el-aside>
        <el-main class="right">
          <!--通过点击左边菜单，动态显示不同组件 -->
          <component :is=currentComponent></component>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>


<script setup>
import MenuItem from '../components/MenuItem.vue';
import AddCustomer from "./AddCustomer.vue";
import ListCustomer from "./ListCustomer.vue";
import AddSalesProcess from "./AddSalesProcess.vue";
import AfterSalesService from "./AfterSalesService.vue";
import CustomerAnalysisAndDecisionMaking from "./CustomerAnalysisAndDecisionMaking.vue";
import ListSalesProcess from "./ListSalesProcess.vue"
import CustomerOrderList from "./CustomerOrderList.vue"
import AfterSalesList from "./AfterSalesList.vue"
import {markRaw, nextTick, onMounted, ref} from "vue";
import axios from 'axios';
import {ElMessage} from "element-plus";

//声明数组保存所有组件
const views = [
  markRaw(ListCustomer),
  markRaw(AddCustomer),
  markRaw(AddSalesProcess),
  markRaw(AfterSalesService),
  markRaw(CustomerAnalysisAndDecisionMaking),
  markRaw(ListSalesProcess),
  markRaw(CustomerOrderList),
  markRaw(AfterSalesList)
]
//声明变量保存当前需要显示的组件名
let currentComponent = ref(null);
//声明菜单对象集合数据
const menus = ref([]);
/*menu组件选中叶子节点触发的函数，参数index：菜单节点的index值，对应数据库菜单节点的id*/
const handlerSelect = function (id) {
  console.log(id);
  //发生ajax请求，加载组件下标
  axios.get("http://localhost:52010/menu/" + id + "/component")
      .then((response) => {
        const idx = Number(response.data);
        nextTick(() => {
          if (views[idx]) {
            currentComponent.value = views[idx];
          } else {
            currentComponent.value = null; // 或报错提示
            console.warn('菜单映射组件失败，索引不存在:', idx);
            ElMessage.error(`菜单映射组件失败，索引不存在: ${idx}`);
          }
        });
      })
      .catch((error) => {
        ElMessage.error(error);
        console.log(error);
      });
}
//页面加载，发生ajax请求加载左侧菜单信息
onMounted(function () {
  axios.get("http://localhost:52010/menu/sidebar")
      .then((response) => {
        console.log(response);
        //将响应的数据绑定到menus，实现数据渲染
        menus.value = response.data;
      })
      .catch((error) => {
        console.log(error);
        ElMessage.error(error);
      });
});
</script>

<style scoped>

.top {
  background-color: azure;
  min-width: 100px;
  padding-top: 15px;
}

.left {
  min-width: 100px;
  background-color: blanchedalmond;
  height: 600px;
}

.right {
  background-color: cornsilk;
  /* 让右侧自动分配剩余宽度 */
  flex: 1 1 0;
  width: 300px; /* 或一个合适的最小宽度 */
}

</style>